#网格交易算法 利用行情震荡进行获利的策略，在标的价格不断震荡的过程中，对标的价格绘制网格，在市场价格触碰到某个网格线时进行加减仓操作尽可能获利
#实现逻辑，不停的获取当前股票的价格，利用当前价格作为参照，设定买入和卖出信号，不停的进行交易，并输出所获取的利益成本及收益
import capital_info
import time
import decimal

start_store = 0
rate = 0.02
current_store = 0
cost = 0
earn_money = 0

def grid_algorithm():
    price_sql = "select cast(f2 as decimal(22,2)) from stock_info.cfg_history_data where id = '002242' order by wtime asc"
    result = [j[0] for j in capital_info.get_table_info(price_sql)]
    for i in range(len(result)):
        if i == 0:
            start_store = 10000
            current_store = 10000
            cost = start_store * result[i]
            print('当前仓位买入%d股 总成本为%d\n'%(start_store,cost))
        else:
            if result[i-1] * decimal.Decimal('1.02') < result[i]:
                current_store -= 100
                global earn_money
                earn_money = (earn_money + ((result[i] - result[i-1]) * 100))
                cost -= result[i] * 100
                print("当前仓位中股票数量为%f 总利润为%f 总成本为%f\n"%(current_store,earn_money,cost))
            elif result[i-1] * decimal.Decimal('1.02') > result[i]:
                current_store += 100
                earn_money += ((result[i] - result[i-1]) * 100)
                cost += result[i] * 100
                print("当前仓位中股票数量为%f 总利润为%f 总成本为%f\n" % (current_store, earn_money,cost))
            else:
                pass
        time.sleep(1)

if __name__ == '__main__':
    grid_algorithm()
    # print(1+rate)
    # print(type(1+rate))
